package top.jiangqiang.qyblog.common.utils;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.servlet.JakartaServletUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.MediaType;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import top.jiangqiang.qyblog.common.base.response.Result;
import top.jiangqiang.qyblog.common.constant.ResponseEnum;

import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

/**
 * @author jiangqiang
 * @date 2022-07-31
 */
public class ServletUtil extends JakartaServletUtil {
    public static void writeJson(HttpServletResponse response, ResponseEnum responseEnum) {
        writeJson(response, Result.build(responseEnum));
    }

    public static void writeJson(HttpServletResponse response, Result<?> result) {
        writeJson(response, result.toString());
    }

    public static void writeJson(HttpServletResponse response, String json) {
//        write(response, json, MediaType.APPLICATION_JSON_VALUE);
        write(response, json, MediaType.APPLICATION_JSON_UTF8_VALUE);
    }

    public static void write(HttpServletResponse response, File file, String mimeType) {
        // 设置 header 和 contentType
        response.setContentType(mimeType);
        // 输出附件
        write(response, IoUtil.toStream(file));
    }

    /**
     * 返回附件
     *
     * @param response 响应
     * @param filename 文件名
     * @param content  附件内容
     * @throws IOException
     */
    public static void writeAttachment(HttpServletResponse response, String filename, byte[] content) throws IOException {
        // 设置 header 和 contentType
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, StandardCharsets.UTF_8));
        response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
        // 输出附件
        IoUtil.write(response.getOutputStream(), true, content);
    }

    /**
     * 获取域名部分
     *
     * @return
     */
    public static String getHostFromRequest() {
        String requestURL = getRequest().getRequestURL().toString();
        requestURL = StrUtil.removePrefix(requestURL, "http://");
        requestURL = StrUtil.removePrefix(requestURL, "https://");
        requestURL = StrUtil.subBefore(requestURL, "/", false);
        return requestURL;
    }


    public static HttpServletRequest getRequest() {
        return ((ServletRequestAttributes) (RequestContextHolder.currentRequestAttributes())).getRequest();
    }
}
